package ynu.sxp.demoapp.cart.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.sxp.demoapp.cart.entity.CartEntity;
import ynu.sxp.demoapp.cart.entity.CartProductEntity;
import ynu.sxp.demoapp.cart.repository.CartProductRepository;
import ynu.sxp.demoapp.cart.repository.CartRepository;
import ynu.sxp.demoapp.product.entity.ProductEntity;
import ynu.sxp.demoapp.product.repository.ProductRepository;
import ynu.sxp.demoapp.user.entity.UserEntity;
import ynu.sxp.demoapp.user.repository.UserRepository;

import java.util.Optional;
import java.util.UUID;

@Service
public class CartService {
    private final CartRepository cartRepository;
    private final ProductRepository productRepository;
    private final UserRepository userRepository;
    private final CartProductRepository cartProductRepository;

    @Autowired
    public CartService(CartRepository cartRepository, ProductRepository productRepository, UserRepository userRepository, CartProductRepository cartProductRepository) {
        this.cartRepository = cartRepository;
        this.productRepository = productRepository;
        this.userRepository = userRepository;
        this.cartProductRepository = cartProductRepository;
    }

    @Transactional
    public CartEntity addProductToCart(UUID userId, UUID productId, int quantity) {
        UserEntity user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        ProductEntity product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("Product not found"));

        CartEntity cart = cartRepository.findByUser(user);
        if (cart == null) {
            cart = new CartEntity();
            cart.setUser(user);
        }

        Optional<CartProductEntity> existingCartProduct = cart.getCartProducts().stream()
                .filter(cp -> cp.getProduct().equals(product))
                .findFirst();
        //如果商品已经在购物车中，更新其数量
        if (existingCartProduct.isPresent()) {
            CartProductEntity cartProduct = existingCartProduct.get();
            cartProduct.setQuantity(cartProduct.getQuantity() + quantity);
        } else {
            CartProductEntity cartProduct = new CartProductEntity();
            cartProduct.setCartId(cart.getId());
            cartProduct.setProduct(product);
            cartProduct.setQuantity(quantity);
            cartProductRepository.save(cartProduct);
            cart.getCartProducts().add(cartProduct);
        }
        return cartRepository.save(cart);
    }

    @Transactional
    public CartEntity removeProductFromCart(UUID userId, UUID productId) {
        UserEntity user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        ProductEntity product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("Product not found"));
        CartEntity cart = cartRepository.findByUser(user);
        if (cart == null) {
            throw new RuntimeException("Cart not found for user");
        }

        Optional<CartProductEntity> cartProductOpt = cart.getCartProducts().stream()
                .filter(cp -> cp.getProduct().equals(product))
                .findFirst();

        if (cartProductOpt.isPresent()) {
            CartProductEntity cartProduct = cartProductOpt.get();
            cart.getCartProducts().remove(cartProduct);
            cartProductRepository.delete(cartProduct);
        } else {
            throw new RuntimeException("Product not found in the cart");
        }
        return cartRepository.save(cart);
    }

    @Transactional
    public CartEntity getCartByUser(UUID userId) {
        UserEntity user = userRepository.findById(userId).orElseThrow(() -> new RuntimeException("User not found"));
        return cartRepository.findByUser(user);
    }

    @Transactional
    public CartEntity createCart(UUID userId) {
        UserEntity user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));

        CartEntity cart = new CartEntity();
        cart.setUser(user);
        cart = cartRepository.save(cart);
        return cart;
    }

    @Transactional
    public CartEntity getCartById(UUID cartId) {
        return cartRepository.findById(cartId).get();
    }
}
